package icangyu.base.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import icangyu.base.R;


/**
 * Created by 200h on 2016/10/18.
 */
public class ImageLoader {

    public static final int CENTER_CROP = 0;
    public static final int CENTER_INSIDE = 1;
    public static final int FIT_CENTER = 2;


    private static boolean checkContext(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            if (Build.VERSION.SDK_INT >= 17)
                return !(activity.isFinishing() || activity.isDestroyed());
            return !activity.isFinishing();
        }
        return false;
    }

    private static RequestOptions getOption(@DrawableRes int placeHolder, int scaleType) {
        RequestOptions options = new RequestOptions();
        if (placeHolder != 0) {
            options.placeholder(placeHolder).error(placeHolder);
        }
        if (scaleType == CENTER_CROP) {
            options.centerCrop();
        } else if (scaleType == CENTER_INSIDE) {
            options.centerInside();
        } else if (scaleType == FIT_CENTER) {
            options.fitCenter();
        } else if (scaleType == 3) {

        }
        return options;
    }

    public static void showCover(Context context, ImageView view, String path) {
        show(context, view, path, R.drawable.def_cover);
    }

    public static void showThumb(ImageView view, String path) {
        if(view!=null) {
            if (checkContext(view.getContext()) && !TextUtils.isEmpty(path)) {
                String s ;
                if (!path.startsWith("http")) {
                    s = ServerConfig.getBaseUrl() + path;
                }else {
                    s = path+ "-thumbImage";
                }
                Glide.with(view.getContext()).load(s).apply(getOption(R.drawable.def_cover, CENTER_CROP)).into(view);
            } else {
                view.setImageResource(R.drawable.def_cover);
            }
        }
    }

    public static void showCover(ImageView view, String path) {
        if (view != null) {
            show(view.getContext(), view, path, R.drawable.def_cover);
        }
    }

    public static void showAvatar(Context context, ImageView view, String path) {
        show(context, view, path, R.drawable.default_avatar);
    }

    public static void showAvatar(ImageView view, String path) {
        if (view != null) {
            show(view.getContext(), view, path, R.drawable.default_avatar);
        }
    }

    public static void showAvatarThumb(ImageView view, String path) {
        if(view!=null) {
            if (checkContext(view.getContext()) && !TextUtils.isEmpty(path)) {
                if (!path.startsWith("http")) {
                    path = ServerConfig.getBaseUrl() + path;
                }else {
                    path += "-thumbImage";
                }
                Glide.with(view.getContext()).load(path).apply(getOption(R.drawable.default_avatar, 0)).into(view);
            } else {
                view.setImageResource(R.drawable.default_avatar);
            }
        }
    }

    public static void show(Context context, ImageView view, String path, @DrawableRes int placeHolder){
        if(checkContext(context) && !TextUtils.isEmpty(path)) {
            if(!path.startsWith("http")) {
                path = ServerConfig.getBaseUrl() +path;
            }
            Glide.with(context).load(path).apply(getOption(placeHolder,CENTER_CROP)).into(view);
        }else {
            view.setImageResource(placeHolder);
        }
    }

    public static void showOrigin(final ImageView view, String path, @DrawableRes int placeHolder){
        if(view == null ) return;
        if(checkContext(view.getContext()) && !TextUtils.isEmpty(path)) {
            if(!path.startsWith("http")) {
                path = ServerConfig.getBaseUrl() + path;
            }
            Glide.with(view.getContext()).load(path).listener(
                    new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            if(resource == null){
                                return false;
                            }
                            ViewGroup.LayoutParams params = view.getLayoutParams();
                            if(params!=null) {
                                params.height = resource.getIntrinsicHeight() * params.width / resource.getIntrinsicWidth();
                            }
                            view.setLayoutParams(params);
                            view.setImageDrawable(resource);
                            return false;
                        }
                    }
            ).apply(getOption(placeHolder,3)).preload();
        }else {
            view.setImageResource(placeHolder);
        }
    }

    public static void showOrFile(Context context, ImageView view, String path){
        if(!TextUtils.isEmpty(path)) {
            if(path.startsWith("/storage")||path.startsWith("/data")){
                showFile(context,view, new File(path),false);
                return;
            }else if(!path.startsWith("http")) {
                path = ServerConfig.getBaseUrl() + path;
            }else {
                path += "-thumbImage";
            }
            Glide.with(context).load(path).apply(getOption(R.drawable.def_cover, CENTER_CROP)).into(view);
        }else {
            view.setImageResource(R.drawable.def_cover);
        }
    }

    public static void showOrFile(Context context, ImageView view, String path, @DrawableRes int placeHolder,int option){
        if(!TextUtils.isEmpty(path)) {
            if(path.startsWith("/storage")||path.startsWith("/data")){
                showFile(context,view, new File(path),false);
                return;
            }else if(!path.startsWith("http")) {
                path = ServerConfig.getBaseUrl() + path;
            }
            Glide.with(context).load(path).apply(getOption(placeHolder,option)).into(view);
        }else {
            view.setImageResource(placeHolder);
        }
    }

    public static void show(Context context,ImageView view,String path){
        if(checkContext(context) && !TextUtils.isEmpty(path)) {
            if(!path.startsWith("http")) {
                path = ServerConfig.getBaseUrl()+path;
            }
            Glide.with(context).load(path).apply(getOption(R.drawable.def_cover,FIT_CENTER)).into(view);
        }
    }

    public static void show(Context context, ImageView view, Drawable drawable){
        if(checkContext(context) && drawable != null){
            Glide.with(context).load(drawable).apply(getOption(0,CENTER_CROP)).into(view);
        }
    }

    /**
     * 显示本地资源
     *
     * @param context
     * @param view
     * @param drawable
     */
    public static void showResource(Context context, ImageView view,@DrawableRes int drawable){
        if(checkContext(context) ){
            Glide.with(context).load(drawable).apply(getOption(R.drawable.def_cover,CENTER_CROP)).into(view);
        }
    }

    public static void showUri(Context context, ImageView view, Uri uri){
        if(checkContext(context)){
            Glide.with(context).load(uri).apply(getOption(R.drawable.def_cover,CENTER_CROP)).into(view);
        }
    }

    public static void showFile(Context context, ImageView view, File file,boolean isFull){
        if(checkContext(context)){
            RequestOptions options = new RequestOptions();
            options.error(R.drawable.def_cover);
            if(isFull){
                options.centerCrop();
            }else {
                options.fitCenter();
            }
            Glide.with(context).load(file).apply(options).into(view);
        }
    }

    public static void showFile(Context context, ImageView view, File file,int width, int height, boolean isFull){
        if(checkContext(context)){
            RequestOptions options = new RequestOptions();
            options.error(R.drawable.def_cover);
            if(isFull){
                options.centerCrop();
            }else {
                options.fitCenter();
            }
            if(width>0&&height>0){
                options.override(width,height);
            }
            Glide.with(context).load(file).apply(options).into(view);
        }
    }

    public static void cacheImage(final Context context , final ThreadPoolExecutor pool, final String url, final OnLoadFinished listener){
        if(pool != null){
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    File file = null;
                    try {
                        file = Glide.with(context)
                                .load(ServerConfig.getBaseUrl(url))
                                .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                .get();
                        LogUtils.b(new StringBuilder()
                                .append("url:").append(url)
                                .append("\nfilePath:").append(file.getAbsoluteFile())
                                .append("\nfileSize:").append(FileUtils.formatFileSize(file.length()))
                                .toString());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } finally {
                        if (listener != null) {
                            listener.onFinished(file);
                        }
                    }
                }
            });
        }

    }


}
